﻿using CnBlogsClient.Global;
using CnBlogsClient.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace CnBlogsClient.Views.News
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class NewsPage : ContentPage
    {
        NewsViewModel ViewModel => vm ?? (vm = BindingContext as NewsViewModel); 
        NewsViewModel vm;

        bool hasInitialization;
        int position = 0;
        public NewsPage(int position = 0) : base()
        {
            this.position = position;
            InitializeComponent();

            Xamarin.Forms.NavigationPage.SetHasNavigationBar(this, false);
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            if(!hasInitialization)
            {
                BindingContext = new NewsViewModel(position);

                this.newsListView.ItemSelected += async delegate {
                    var news = newsListView.SelectedItem as CnBlogsCore.Model.News;
                    this.newsListView.SelectedItem = null;

                    if (news == null)
                        return;

                    var detailPage = new NewsDetailsPage(news);
                    await NavigationService.PushAsync(Navigation, detailPage);
                };

                hasInitialization = true;
            }

            UpdatePage();
        }

        private void UpdatePage()
        {
            bool forceRefresh = (DateTime.Now > (ViewModel?.NextRefreshTime ?? DateTime.Now));
            if(forceRefresh)
            {
                ViewModel.RefreshCommand.Execute(null);
            }
        }
    }
}